#!/bin/bash
#
# AppImage builder with Miniconda3
#
# You need to run "make dists" before running the script
#

COMMIT_SHORT=$(echo $TRAVIS_COMMIT|cut -c 1-8)

MINICONDA_DIST="Miniconda3-py37_4.8.3-Linux-x86_64.sh"
GO_IPFS_VERSION=0.8.0
GOIPFS_TGZ="go-ipfs_v${GO_IPFS_VERSION}_linux-amd64.tar.gz"
GOIPFS_DISTURL="https://dist.ipfs.io/go-ipfs/v${GO_IPFS_VERSION}/${GOIPFS_TGZ}"

if [ $# -lt 1 ]; then
    G_VERSION=$(grep '__version__' ../galacteek/__init__.py|sed -e "s/__version__\s=\s'\(.*\)'$/\1/")
else
    G_VERSION=$1
fi

if [[ $TRAVIS_BRANCH =~ ^v([0-9].[0-9].[0-9]{1,2}) ]] ; then
    echo "Using tag: $TRAVIS_BRANCH"
    EVERSION=${BASH_REMATCH[1]}
    APPIMAGE_DEST="Galacteek-${EVERSION}-x86_64.AppImage"
    APPIMAGE_FULL_DEST="Galacteek-wasmer-${EVERSION}-x86_64.AppImage"
else
    if [ "$TRAVIS_BRANCH" != "master" ]; then
        echo "Short commit ID: ${COMMIT_SHORT}"
        APPIMAGE_DEST="Galacteek-${COMMIT_SHORT}-x86_64.AppImage"
        APPIMAGE_FULL_DEST="Galacteek-wasmer-${COMMIT_SHORT}-x86_64.AppImage"
    else
        APPIMAGE_DEST="Galacteek-${G_VERSION}-x86_64.AppImage"
        APPIMAGE_FULL_DEST="Galacteek-wasmer-${G_VERSION}-x86_64.AppImage"
    fi
fi

echo "Travis commit: ${TRAVIS_COMMIT}"
echo "Building AppImage for version: ${G_VERSION}"

if ! [ -e $MINICONDA_DIST ]; then
    wget "https://repo.anaconda.com/miniconda/${MINICONDA_DIST}"
    md5=$(md5sum ${MINICONDA_DIST}|awk '{print $1}')

    if [ "$md5" != "751786b92c00b1aeae3f017b781018df" ]; then
        echo "${MINICONDA_DIST}: invalid checksum"
        exit 1
    else
        echo "${MINICONDA_DIST}: checksum is valid"
    fi
fi

if [ "$TRAVIS_BRANCH" = "catalyst-ipfs-dev" ]; then
    # Compile from master
    git clone https://github.com/ipfs/go-ipfs.git $HOME/go-ipfs.git
    pushd $HOME/go-ipfs.git
    make build
    cp cmd/ipfs/ipfs $HOME/bin/ipfs
    popd
else
    wget $GOIPFS_DISTURL
    sha=$(sha512sum ${GOIPFS_TGZ}|awk '{print $1}')

    if [ "$sha" != "1d5910f27e8d7ea333145f15c6edcbacc1e8db3a99365f0847467bdfa7c73f4d7a05562e46be8e932056c8324ed0769ca1b6758dfb0ac4c2e1b6066b57c4a086" ]; then
        echo "${GOIPFS_TGZ}: invalid checksum"
        exit 1
    fi

    tar -C /tmp -xzvf ${GOIPFS_TGZ}
    mv /tmp/go-ipfs/ipfs $HOME/bin/ipfs
fi

APPDIR="galacteek.AppDir.${G_VERSION}"
APPIPIP=$APPDIR/usr/bin/pip
WHEEL=../dist/galacteek-$G_VERSION-py3-none-any.whl

if ! [ -e $WHEEL ]; then
    echo "Wheel for version $G_VERSION does not exist, run make dists"
    exit 1
fi

if [ -e $APPDIR ]; then
    echo "$APPDIR already exists"
else
    mkdir -p $APPDIR
    mkdir -p $APPDIR/usr/share/applications
    mkdir -p $APPDIR/usr/share/licenses/galacteek
    mkdir -p $APPDIR/usr/share/metainfo
    mkdir -p $APPDIR/usr/share/icons/hicolor/512x512/apps
fi

if ! [ -e $APPIPIP ]; then
    echo "Installing miniconda"
    bash $MINICONDA_DIST -b -p "$APPDIR"/usr -f
else
    echo "Miniconda found, continuing"
fi

export PATH="$PATH:$APPDIR/usr/bin"

# Enter the venv
. "$APPDIR"/usr/bin/activate

# Install necessary conda packages
conda install -y -c conda-forge libxkbcommon pip
conda install -y --no-deps libxcb

conda remove -y icu

$APPIPIP install --upgrade pip
$APPIPIP install wheel

# Install the wheel from local dists

echo "Installing wheel: $WHEEL"
$APPIPIP install $WHEEL

cp ../{LICENSE,LICENSE.go-ipfs,LICENSE.Qt.GPLv3} \
	$APPDIR/usr/share/licenses/galacteek
cp ../galacteek.desktop $APPDIR/usr/share/applications
cp ../galacteek.desktop $APPDIR
cp ../galacteek.appdata.xml $APPDIR/usr/share/metainfo
cp ../share/icons/galacteek.png $APPDIR
cp ../share/icons/galacteek.png $APPDIR/usr/share/icons/hicolor/512x512/apps
find /usr/lib -iname 'libzbar.so*' -exec cp -av {} $APPDIR/usr/lib \;
find /usr/lib -iname 'libjpeg.so*' -exec cp -av {} $APPDIR/usr/lib \;

# Copy go-ipfs and fs-repo-migrations
cp $HOME/bin/ipfs $APPDIR/usr/bin
cp $HOME/bin/fs-repo-migrations $APPDIR/usr/bin

# Remove unnecessary stuff
pushd "$APPDIR"/usr

rm -rf pkgs
find -type d -iname '__pycache__' -print0 | xargs -0 rm -r

# Strip everything but the Pillow shared libs
find . -type f -not \( -path ./lib/python3.7/site-packages/PIL -prune \) -o \
	-name '*.so*' -print -exec strip '{}' \;
find -type f -iname '*.a' -print -delete

rm -rf lib/cmake/
rm -rf include/
rm -rf share/{gtk-,}doc
rm -rf bin/tcl*
rm -rf bin/lz*
rm -rf bin/xz*
rm -rf lib/libtcl*
rm -rf lib/libtk*
rm -rf lib/tk*
rm -rf lib/tcl*
rm -rf lib/python3.7/site-packages/Cryptodome/SelfTest/*
rm -rf lib/python3.7/site-packages/PyQt5/Qt/plugins/geoservices
rm -rf lib/python3.7/site-packages/PyQt5/Qt/plugins/sceneparsers
rm -rf lib/python3.7/site-packages/pyzbar/tests
rm -rf lib/python3.7/turtledemo/
rm -rf lib/python3.7/tkinter/
rm -rf lib/python3.7/lib2to3/
rm -rf lib/python3.7/idlelib
rm -rf lib/python3.7/site-packages/git/test
rm -rf lib/python3.7/site-packages/conda_package_handling
rm -rf lib/python3.7/ensurepip
rm -rf lib/python3.7/site-packages/{setuptools,pip}
rm -rf share/man
rm -rf share/readline
rm -rf share/terminfo
rm -rf share/info
rm -rf ssl/man
rm -f lib/libstdc++*

# Remove xcb libs according to the excludelist
rm -f lib/libxcb-dri2.so*
rm -f lib/libxcb-dri3.so*
rm -f lib/libxcb.so*

# QT
TSL_PATH=./lib/python3.7/site-packages/PyQt5/Qt/translations
find $TSL_PATH -type f -not -iname "*en*" -a -not -iname "*es*" \
	-a -not -iname "*fr*" -exec rm {} \;

rm -rf lib/python3.7/site-packages/PyQt5/Qt/plugins/sqldrivers
rm -rf lib/python3.7/site-packages/PyQt5/Qt/lib/libQt5XmlPatterns*
rm -rf lib/python3.7/site-packages/PyQt5/Qt/lib/libQt5Designer*
find lib/python3.7/site-packages/PyQt5/Qt/qml/ -name *.qml -exec rm {} \;
find lib/python3.7/site-packages/PyQt5/Qt/qml/ -name *.qmlc -exec rm {} \;
find lib/python3.7/site-packages/PyQt5/Qt/qml/QtQuick -exec rm {} \;
rm -rf lib/python3.7/site-packages/PyQt5/Qt/qml/QtCharts/designer/images
rm -rf lib/python3.7/site-packages/PyQt5/Qt/qml/Qt/labs

python3 -m compileall lib/python3.7/site-packages/galacteek

popd

# Copy the AppRun

cp AppRun $APPDIR/AppRun
chmod 755 $APPDIR/AppRun

sed -i -e 's/#\!\/.*$/#!\/usr\/bin\/python3/' $APPDIR/usr/bin/galacteek
sed -i -e 's/#\!\/.*$/#!\/usr\/bin\/python3/' $APPDIR/usr/bin/mkdocs

wget https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage
chmod +x appimagetool*.AppImage

echo "AppDir successfully created, running appimagetool"
ARCH=x86_64 ./appimagetool-x86_64.AppImage -n $APPDIR $APPIMAGE_DEST

APPIMAGE_CID=$($HOME/bin/ipfs add -q -n --cid-version 1 $APPIMAGE_DEST)
echo "==> CIDv1 $APPIMAGE_DEST: $APPIMAGE_CID"
